package com.longcai.cm.exception;

import com.longcai.cm.bean.R;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.io.IOException;
import java.net.UnknownHostException;

/**
 * 异常处理器
 *
 * @author Libingxing
 */
@RestControllerAdvice
public class SysRuntimeExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(SysRuntimeException.class)
    public R<String> handleSysRuntimeException(SysRuntimeException e) {
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(IOException.class)
    public R<String> handleIoException(IOException e) {
        logger.error(e.getMessage(), e);
        return R.error("网络错误!");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<String> handleIoException(HttpRequestMethodNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return R.error("该方法" + e.getMethod() + "请求方式不支持");
    }

    @ExceptionHandler(UnknownHostException.class)
    public R<String> handleUnknownHostException(UnknownHostException e) {
        logger.error(e.getMessage(), e);
        return R.error("网络错误!");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public R<String> handlerNoFoundException(MaxUploadSizeExceededException e) {
        logger.error(e.getMessage(), e);
        return R.error("文件过大");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return R.error("记录重复!");
    }

    @ExceptionHandler(AuthorizationException.class)
    public R<String> handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        return R.error("无权限");
    }

    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.error("系统繁忙!");
    }
}
